import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/api/interface/home_api.dart';
import 'package:sptapp/api/request/response_data.dart';
import 'package:sptapp/config/const.dart';
import 'package:sptapp/widget/cache_image.dart';
import 'package:sptapp/widget/common_widget.dart';

import '../../moudle/common_info.dart';
import '../../moudle/location/location_tool.dart';

class MinAiGuardPage extends StatefulWidget {
  const MinAiGuardPage({super.key});

  @override
  State<MinAiGuardPage> createState() => _MinAiGuardPageState();
}

class _MinAiGuardPageState extends State<MinAiGuardPage> {

  bool isAiMode = true;
  String address = '';
  Map? addMap;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getDevicesList((){
      if(baseDevice?['stormState']!=null && baseDevice?['stormState'].toString() == '0'){
        isAiMode = false;
      }else{
        isAiMode = true;
      }
      if(mounted){
        setState(() {});
      }
    });
    _getAiMode();
  }
  _showCloseDialog(){
    SmartDialog.show(builder: (ctx){
      return Container(
        width: 680.w,
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        decoration: BoxDecoration(
            color: Color(0xff1e1d20),
            borderRadius: BorderRadius.circular(16.w)
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              height: 112.w,
              decoration: BoxDecoration(
                  border: Border(bottom: BorderSide(color: Color.fromRGBO(255, 255, 255, 0.1),width: 1.w))
              ),
              child: Stack(
                children: [
                  Container(
                    height: 112.w,
                    alignment: Alignment.center,
                    child: Text('AI Guard'.tr,style: TextStyle(
                        color: Colors.white,
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w600
                    ),),
                  ),
                  Positioned(child: GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Container(
                      padding: EdgeInsets.only(top: 24.w,),
                      child: Image.asset('assets/common/common_close.png',width: 48.w,),
                    ),
                  ),top: 0,right: 0,)
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.symmetric(vertical: 48.w),
              alignment: Alignment.center,
              child: Text('AI Guard mode will deactivate during the current weather event.'.tr,style: TextStyle(
                  color: Colors.white,
                  fontSize: 32.sp,
                  fontWeight: FontWeight.w600
              ),),
            ),
            Container(
              height: 108.w,
              child:  Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(child: GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Container(
                      height: 108.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: Color.fromRGBO(255, 255, 255, 0.1),
                        borderRadius: BorderRadius.circular(8.w)
                      ),
                      child: Text('Cancel'.tr,style: TextStyle(
                        color: Colors.white,
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w600
                      ),),
                    ),
                  )),
                  SizedBox(width: 40.w,),
                  Expanded(child: GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                      setState(() {
                        isAiMode = !isAiMode;
                      });
                      _saveAiMode();
                    },
                    child: Container(
                      height: 108.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: themeColor,
                          borderRadius: BorderRadius.circular(8.w)
                      ),
                      child: Text('Continue'.tr,style: TextStyle(
                          color: Colors.white,
                          fontSize: 32.sp,
                          fontWeight: FontWeight.w600
                      ),),
                    ),
                  )),
                ],
              ),
            ),
            SizedBox(height: 40.w,),
          ],
        ),
      );
    },alignment: Alignment.center);
  }

  _getAiMode()async{
    Map<String,dynamic> data = {
      'sn':baseDeviceNum
    };
    showLoading();
    ResponseData res = await HomeAPI.getEquipmentCity(data);
    hideLoading();
    if(res.code == 200 && res.data != null){
      addMap = res.data;
      if(res.data['STATE_NAME'] != null){
        address = res.data['STATE_NAME'];
      }
      if(res.data['CITY'] != null){
        address = '$address ${res.data['CITY']}';
      }
      // if(res.data['address'] != null){
      //   address = '$address ${res.data['address']}';
      // }
    }
    if(mounted){setState(() {});}
  }

  _saveAiMode()async{
    Map<String,dynamic> data = {
      'sn':baseDeviceNum,
      'stormState': isAiMode?'1':'0'
    };
    showLoading();
    ResponseData res = await HomeAPI.deviceSetName(data);
    hideLoading();
    if(res.code == 200){
      baseDevice?['stormState'] = isAiMode?'1':'0';
    }else{
      setState(() {
        isAiMode = !isAiMode;
      });
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      appBar: myAppBar(context, 'AI Guard'.tr),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        child: Column(
          children: [
            Container(
              height: 116.w,
              child: Row(
                children: [
                  Expanded(child: Text('AI Guard'.tr,style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600
                  ),)),
                  SizedBox(width: 24.w,),
                  GestureDetector(
                    onTap: (){
                      if(isAiMode){
                        _showCloseDialog();
                        return;
                      }
                      setState(() {
                        isAiMode = !isAiMode;
                      });
                      _saveAiMode();
                    },
                    child: Image.asset(isAiMode?'assets/common/switch_btn_open.png':'assets/common/switch_btn_close.png',width: 92.w,),
                  )
                ],
              ),
            ),
            Container(
              child: CacheImage(
                image: 'assets/common/min_ai_guard_bg.png',width: 670.w,
              ),
            ),
            SizedBox(height: 20.w,),
            Container(
              child: Text('When extreme weather is predicted, SPT will turn on AI Guard function, automatically charging your battery to full capacity. This ensures maximum power availability to meet your energy needs in case the Grid becomes unavailable.',
              style: TextStyle(
                color: Color.fromRGBO(255, 255, 255, 0.5),
                fontSize: 24.sp,
                fontWeight: FontWeight.w400
              ),),
            ),
            SizedBox(height: 80.w,),
            Visibility(visible: isAiMode,child: Container(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('AI Guard Location'.tr,style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600
                  ),),
                  Text('AI Guard uses your home location to determine if a weather event will impact your home.'.tr,style: TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                      fontSize: 24.sp,
                      fontWeight: FontWeight.w600
                  ),),
                  SizedBox(height: 20.w,),
                  GestureDetector(
                    onTap: (){
                      Navigator.of(context).pushNamed('MinChooseAddressPage',arguments: addMap).then((val){
                        _getAiMode();
                      });
                    },
                    child: Container(
                      height: 116.w,
                      decoration: BoxDecoration(
                        border: Border(top: BorderSide(color: Color.fromRGBO(255, 255, 255, 0.1),width: 1.w),bottom: BorderSide(color: Color.fromRGBO(255, 255, 255, 0.1),width: 1.w))
                      ),
                      child: Row(
                        children: [
                          Image.asset('assets/common/min_ai_location.png',width: 40.w,),
                          SizedBox(width: 4.w,),
                          Text('Region'.tr,style: TextStyle(
                              color: Colors.white,
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w600
                          ),),
                          SizedBox(width: 24.w,),
                          Expanded(child: Text(address??'',style: TextStyle(
                              color: Colors.white,
                              fontSize: 24.sp,
                              fontWeight: FontWeight.w600
                          ),textAlign: TextAlign.right,overflow: TextOverflow.ellipsis,maxLines: 1,)),
                          Image.asset('assets/common/control_right.png',width: 48.w,)
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),)
          ],
        ),
      ),
    );
  }
}
